/*******************************************************************************
 * Copyright (c) 2012 March and Conquest.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package mrusanov.towers.net;

import java.awt.EventQueue;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import mrusanov.towers.configuration.GamefieldConfiguration;
import mrusanov.towers.main.DesktopGame;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class CommunicatorThread implements Runnable {

	private static final Logger LOG = LoggerFactory.getLogger(CommunicatorThread.class);

	private final BlockingQueue<CommunicatorTask> taskQueue = new LinkedBlockingQueue<CommunicatorTask>();

	protected final Communicator communicator = new Communicator();
	protected final DesktopGame game;

	public CommunicatorThread(DesktopGame game) {
		super();
		this.game = game;
	}

	@Override
	public void run() {
		try {
			initCommunicator();

			boolean active = true;
			while (active && !Thread.interrupted() && communicator.isActive()) {

				CommunicatorTask task = taskQueue.take();
				LOG.info("Picked up task  {}", task);
				executeCommunicatorTask(task);

				if (task instanceof EndCommunicationTask) {
					active = false;
				}
			}
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
			EventQueue.invokeLater(new Runnable() {

				@Override
				public void run() {
					game.connectionError();
				}
			});
		} catch (final Exception e) {
			LOG.error(e.getMessage(), e);
			EventQueue.invokeLater(new Runnable() {

				@Override
				public void run() {
					game.unknownError(e);
				}
			});
		}

		communicator.dispose();
	}

	void executeCommunicatorTask(final CommunicatorTask task) throws Exception {
		task.executeTask(this);
		EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				task.applyTaskResults(game);
			}
		});
	}

	StartingPlayer receiveStartingPlayer() throws Exception {
		return communicator.receiveStartingPlayer();
	}

	void sendStartingPlayer(StartingPlayer startingPlayer) throws Exception {
		communicator.sendStartingPlayer(startingPlayer);
	}

	void sendPlayerName(String name) throws Exception {
		communicator.sendPlayerName(name);
	}

	String receivePlayerName() throws Exception {
		return communicator.receivePlayerName();
	}

	void sendTurnInfo(TurnInfo info) throws Exception {
		communicator.sendTurnInfo(info);
	}

	TurnInfo receiveTurnInfo() throws Exception {
		return communicator.receiveTurnInfo();
	}

	void sendGamefieldConfiguration(GamefieldConfiguration configuration) throws Exception {
		communicator.sendGamefieldConfiguration(configuration);
	}

	GamefieldConfiguration receiveGamefieldConfiguration() throws Exception {
		return communicator.receiveGamefieldConfiguration();
	}

	public void dispose() {
		taskQueue.add(new EndCommunicationTask());
		communicator.dispose();
	}

	public abstract void initCommunicator();

	public boolean isServer() {
		return communicator.isServer();
	}

	public void addCommunicatorTask(CommunicatorTask task) {
		taskQueue.add(task);
	}
}
